<?php
// +----------------------------------------------------------------------
// | 后台公用模块，所有类都继承此类
// +----------------------------------------------------------------------
// | Author: 李乾坤 <261001642@qq.com>
// +----------------------------------------------------------------------
import("ORG.Util.Cookie");
import("ORG.Util.Session");
class CommonAction extends Action {
    public function _initialize()
    {
        //G('Cansnow');
        //trace(G('Cansnow','Cansnow2').'s');
        //unset($_SESSION['_AUTH_LIST_'.$_SESSION[C('USER_AUTH_KEY')]]);
        $this->checkRule();
        $NOT_AUTH_MODULE=explode(',',C('NOT_AUTH_MODULE'));
        $NOT_AUTH_MODULE[]='Photo';
        if (!in_array(MODULE_NAME,$NOT_AUTH_MODULE) && !$_SESSION[C('ADMIN_AUTH_KEY')]){
            if(!auth()) {
                if($_SESSION[C('USER_AUTH_KEY')]<1) {
                    //跳转到认证网关
                    //$this->error(L('_VALID_ACCESS_'));
                    redirect('?s=/Public/login');
                }
                // 没有权限 抛出错误
                $this->error(L('_VALID_ACCESS_'));
                exit;
            }
        }
		// 读取系统配置参数
        if(!file_exists(DATA_PATH.'~config.php')) {
            $config		=	M("Config");
            $list			=	$config->getField('name,value');
            $savefile		=	DATA_PATH.'~config.php';
            // 所有配置参数统一为大写
            $content		=   "<?php\nreturn ".var_export(array_change_key_case($list,CASE_UPPER),true).";\n?>";
            if(!file_put_contents($savefile,$content)){
                $this->error('配置缓存失败！');
            }
        }
		C(include_once DATA_PATH.'~config.php');
    }
    // 检查用户是否登录
    protected function checkUser() {
        if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
            $this->assign('jumpUrl',U('Public/login'));
            $this->error('没有登录');
        }
    }
    function checkRule($name=null){
        if (is_null($name) && ACTION_NAME!='index'){return;}
        $AuthRule=M('AuthRule');
        $name= is_null($name) ? strtolower(APP_NAME.'/'.MODULE_NAME.'/'.ACTION_NAME): $name;
        $vo=$AuthRule->where('name="'.$name.'"')->find();
        if (!$vo){        
            $arr=array(
                'name'  =>  $name,
                'title' =>  $name,
                'status'   =>1,
            );
            $AuthRule->data($arr)->add();
        }
    }
	// 缓存文件
	public function cache($name='',$fields='') {
		$name	=	$name?	$name	:	$this->getActionName();
		$Model	=	M($name);
		$list		=	$Model->where('status=1')->select();
		$data		=	array();
		foreach ($list as $key=>$val){
			if(empty($fields)) {
				$data[$val[$Model->getPk()]]	=	$val;
			}else{
				// 获取需要的字段
				if(is_string($fields)) {
					$fields	=	explode(',',$fields);
				}
				if(count($fields)==1) {
					$data[$val[$Model->getPk()]]	 =	 $val[$fields[0]];
				}else{
					foreach ($fields as $field){
						$data[$val[$Model->getPk()]][]	=	$val[$field];
					}
				}
			}
		}
        $getCacheFilename   =   $name?  $name   :   $this->getActionName();
		$savefile		=	DATA_PATH.'~'.strtolower($getCacheFilename).'.php';
		// 所有参数统一为大写
		$content		=   "<?php\nreturn ".var_export(array_change_key_case($data,CASE_UPPER),true).";\n?>";
		if(file_put_contents($savefile,$content)){
			$this->success('缓存生成成功！');
		}else{
			$this->error('缓存失败！');
		}
	}
	
    public function index($module='',$tpl='')
    {
        $module=$module ? $module :$this->getActionName();
        //列表过滤器，生成查询Map对象
        $map = $this->_search($module);
        if(method_exists($this,'_filter')) {
            $map =$this->_filter($map);
        }
        //P($map);
        $model        = M($module);
        if(!empty($model)) {
            $this->_list($model,$map);
        }
        $this->display($tpl);
        return;
    }

    /**
     +----------------------------------------------------------
     * 验证码显示
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    function verify()
    {
        import("ORG.Util.Image");
       	Image::buildImageVerify();
    }

    /**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param string $name 数据对象名称
     +----------------------------------------------------------
     * @return HashMap
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    protected function _search($name='')
    {
        //生成查询条件
		if(empty($name)) {
			$name	=	$this->getActionName();
		}
		$model	=	M($name);
		$map	=	array();
		//dump($_REQUEST);
        foreach($model->getDbFields() as $key=>$val) {
            if(substr($key,0,1)=='_') continue;
            if(isset($_REQUEST[$val]) && $_REQUEST[$val]!='') {
                $map[$val]	=	$_REQUEST[$val];
            }
        }
        return $map;
    }

    /**
     +----------------------------------------------------------
     * 根据表单生成查询条件
     * 进行列表过滤
     +----------------------------------------------------------
     * @access protected
     +----------------------------------------------------------
     * @param Model $model 数据对象
     * @param HashMap $map 过滤条件
     * @param string $sortBy 排序
     * @param boolean $asc 是否正序
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    protected function _list($model,$map=array(),$sortBy='',$asc=false)
    {
        //P($map);
        //排序字段 默认为主键名
        if(isset($_REQUEST['_order'])) {
            $order = $_REQUEST['_order'];
        }else {
            $order = !empty($sortBy)? $sortBy: $model->getPk();
        }
        //排序方式默认按照倒序排列
        //接受 sost参数 0 表示倒序 非0都 表示正序
        if(isset($_REQUEST['_sort'])) {
            $sort = $_REQUEST['_sort']?'asc':'desc';
        }else {
            $sort = $asc?'asc':'desc';
        }
        //取得满足条件的记录数
        $count      = $model->where($map)->count('id');
		//echo $model->getlastsql();
        import("@.ORG.Util.Page");
        //创建分页对象
        if(!empty($_REQUEST['listRows'])) {
            $listRows  =  $_REQUEST['listRows'];
        }else {
            $listRows  =  '';
        }
        $p          = new Page($count,$listRows);
        $p->setConfig('theme','<span class="rows"> %totalRow% %header% %nowPage%/%totalPage% 页</span> %upPage% %downPage% %first%  %prePage%  %linkPage%  %nextPage% %end%');
        //分页查询数据
        $list     = $model->where($map)->order($order.' '.$sort)->limit($p->firstRow.','.$p->listRows)->select();
        //echo $model->getlastsql();
		//分页跳转的时候保证查询条件
        foreach($map as $key=>$val) {
            if(!is_array($val)) {
            $p->parameter.="&$key=".urlencode($val);
            }else{
			$p->parameter.="&$key=".urlencode($val[1]);
			}
        }

        //分页显示
        $page       = $p->show();
        //列表排序显示
        $sortImg    = $sort ;                                   //排序图标
        $sortAlt    = $sort == 'desc'?'升序排列':'倒序排列';    //排序提示
        $sort       = $sort == 'desc'? 1:0;                     //排序方式
        //模板赋值显示
		//echo "<pre>";
		//print_r($list);
        $this->assign('list',       $list);
        $this->assign('sort',       $sort);
        $this->assign('order',      $order);
        $this->assign('sortImg',    $sortImg);
        $this->assign('sortType',   $sortAlt);
        $this->assign("page",       $page);
        Cookie::set('_currentUrl_',__SELF__);
        //echo $model->getlastsql();
        return ;
    }

    function insert($module=null,$data=array())
    {
        $module=is_null($module) ? $this->getActionName() : $module ;
        $model  =   D($module);
        $tmp=$_POST;
        if (!empty($data)){
            $_POST=$data;
        }
        if(false === $model->create()) {
            $this->error($model->getError());
        }
        //保存当前数据对象
        if($result = $model->add()) { //保存成功
            // 回调接口
            if(method_exists($this,'_tigger_insert')) {
                $model->id =  $result;
                $model->tags=$_POST['tags'];
                $this->_tigger_insert($model);
            }
            $data=$_POST;
            $this->assign('jumpUrl',$this->getJumpUrl());
            $this->success(L('新增成功'));
        }else {
            $data=$_POST;
            //失败提示
            $this->error(L('新增失败'));
        }
    }

	public function add() {
		$this->display('edit');
	}

	function read($module=null,$tpl='') {
        $this->edit($module,$tpl);
    }

    function edit($module=null,$tpl='') {
        $module=is_null($module) ? $this->getActionName() : $module ;
        $model  =   M($module);
        $id     = $_REQUEST['id'];
        $vo =   $model->find($id);
        $this->assign('vo',$vo);
        $this->display($tpl);
    }
    
    function update($module=null,$data=array()) {
        $module=is_null($module) ? $this->getActionName() : $module ;
        $model  =   D($module);
        $tmp=$_POST;
        if (!empty($data)){
            $_POST=$data;
        }
        if(false === $model->create()) {
            $this->error($model->getError());
        }
        // 更新数据
        if(false !== $model->save()) {
            // 回调接口
            if(method_exists($this,'_tigger_update')) {
                $model->id=$_POST['id'];
                $model->tags=$_POST['tags'];
                $this->_tigger_update($model);
            }
            $data=$_POST;
            $this->assign('jumpUrl',$this->getJumpUrl());
            $this->success(L('更新成功'));
        }else {
            $data=$_POST;
            //错误提示
            $this->error(L('更新失败'));
        }
    }

    /**
     +----------------------------------------------------------
     * 默认列表选择操作
     *
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    protected function select($fields='id,name',$title='')
    {
        $map = $this->_search();
        //创建数据对象
        $Model = M($this->getActionName());
        //查找满足条件的列表数据
        $list     = $Model->where($map)->getField($fields);
		$this->assign('selectName',$title);
        $this->assign('list',$list);
        $this->display();
        return;
    }
    public function delete($module=false)
    {
		//删除指定记录
        if(!$module){
          $module=$this->getActionName();
        }
        $model =   M($module);
        if(!empty($model)) {
			$pk	=	$model->getPk();
            $id         = $_REQUEST[$pk];
            if(isset($id)) {
                $condition = array($pk=>array('in',explode(',',$id)));
                if(false !== $model->where($condition)->delete()){
                    $this->success(L('删除成功'));
                }else {
                    $this->error(L('删除失败').$model->getlastsql());
                }
            }else {
                $this->error('非法操作');
            }
        }
    }
	function _before_del(){
		$ids= explode(',',$_REQUEST["id"]);
		$action=$this->getActionName();
		$ac=$$action=M($action);
		$ac1=str_replace('cate','',$action);
		$ac1=$$ac1=M($ac1);
		foreach($ids as $id){
			$tmp=$ac->where("up=$id")->count('id');
			if ($tmp>0){
				$this->error('该类下面有内容未被删除或移动!');
			}
			$tmp=$ac1->where("cid=$id")->count('id');
			if ($tmp>0){
				$this->error('该类下面有内容未被删除或移动!');
			}
		}
	
	}
    /**
     +----------------------------------------------------------
     * 取得操作成功后要返回的URL地址
     * 默认返回当前模块的默认操作
     * 可以在action控制器中重载
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return string
     +----------------------------------------------------------
     * @throws ThinkExecption
     +----------------------------------------------------------
     */
    function getReturnUrl()
    {
        return 'admin.php?s=/'.MODULE_NAME.'/'.C('DEFAULT_ACTION');
		//return U(MODULE_NAME);
        //return __URL__;
		//return $_SERVER['HTTP_REFERER'];
    }

	function getJumpUrl(){
        return $_REQUEST['jumpurl'] ? $_REQUEST['jumpurl'] : __URL__;
    }
    function uploadone($file,$savepath='./Public/Uploads/',$thumb=false,$ext='',$maxSize=0){
        import("ORG.Net.UploadFile");
        $upload = new UploadFile();
        $upload->maxSize= ($maxSize ==0) ? C('UPLOAD_MAX_SIZE') : $maxSize;
        $upload->allowExts  = explode(',',$ext ? $ext : C('UPLOAD_FILE_EXT'));
        $upload->savePath =  $savepath;
        //执行上传操作
        $uploadList=$upload->uploadOne($file,$savepath);
        if(false==$uploadList) {
            $this->error($upload->getErrorMsg());
        }else {
            $f =    $uploadList[0];
            if($thumb!==false && in_array(strtolower($f['extension']),array('gif','jpg','jpeg','bmp','png'))){
                $thumb=explode(',',$thumb);
                $filename=$f['savepath'].$f['savename'];
                $image =  getimagesize($filename);
                if(false !== $image) {
                    //是图像文件生成缩略图
                    $thumbWidth     =   $thumb[0];
                    $thumbHeight        =   $thumb[1];
                    $thumbPrefix        =   'thu_';
                    // 生成图像缩略图
                    import('ORG.Util.Image');
                    $thumbname  =   $f['savepath'].$thumbPrefix.$f['savename'];
                    Image::thumb($filename,$thumbname,'',$thumbWidth,$thumbHeight,true);
                    if($thumb[2]){
                        // 生成缩略图之后删除原图
                        unlink($filename);
                        $f['savename']=$thumbPrefix.$f['savename'];
                    }
                }
                
            }
            $f['module']    =   $this->getActionName();
            $f['record_id']=    0;
            $f['pid']       =   0;
            $f['remark']    =   '';
            save_attach($f);
            return $f;     
        }
    }
    function upload($savepath='',$thumb=false,$ext='',$maxSize=0){
        $savepath=empty($savepath) ? './Public/Uploads/'.MODULE_NAME.'/' : $savepath;
        foreach($_FILES as $name=>$file){
            if ($file['name']){
                $tmp=$this->uploadone($file,$savepath,$thumb,$ext,$maxSize);
                $_POST[$name]=$tmp['savepath'].$tmp['savename'];
            }
        }
    }

    function saveTag($tags,$id,$module=MODULE_NAME)
    {
        if(!empty($tags) && !empty($id)) {
            $Tag = M("Tag");
            $Tagged   = M("Tagged");
            // 记录已经存在的标签
            $exists_tags  = $Tagged->where("module='{$module}' and record_id={$id}")->getField("id,tag_id");
            $Tagged->where("module='{$module}' and record_id={$id}")->delete();
            $tags = explode(',',$tags);
            foreach($tags as $key=>$val) {
                $val  = trim($val);
                if(!empty($val)) {
                    $tag =  $Tag->where("module='{$module}' and name='{$val}'")->find();
                    if($tag) {
                        // 标签已经存在
                        if(!in_array($tag['id'],$exists_tags)) {
							$Tag->where('id='.$tag['id'])->setInc('count');
                        }
                    }else {
                        // 不存在则添加
						$tag = array();
                        $tag['name'] =  $val;
                        $tag['count']  =  1;
                        $tag['module']   =  $module;
                        $result  = $Tag->add($tag);
                        $tag['id']   =  $result;
                    }
                    // 记录tag关联信息
                    $t = array();
                    $t['user_id'] =$_SESSION[C('USER_AUTH_KEY')];
                    $t['module']   = $module;
                    $t['record_id'] =  $id;
                    $t['create_time']  = time();
                    $t['tag_id']  = $tag['id'];
                    $Tagged->add($t);
                }
            }
        }
    }

  

    /**
     +----------------------------------------------------------
     * 默认排序操作
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     * @throws FcsException
     +----------------------------------------------------------
     */
    public function sort($module=null)
    {
        if (is_null($module)){
            $module=$this->getActionName();
        }
        $model = M($module);
        if(!empty($_GET['sortId'])) {
            $map = array();
            $map['status'] = 1;
            $map['id']   = array('in',$_GET['sortId']);
            $sortList   =   $model->where($map)->order('sort asc')->select();
        }else{
            $sortList   =   $model->where('status=1')->order('sort asc')->select();
        }
        $this->assign("sortList",$sortList);
        $this->display();
        return ;
    }
    public function saveSort()
    {
        $seqNoList  =   $_POST['seqNoList'];
        if(!empty($seqNoList)) {
            //更新数据对象
            $model    = M($this->getActionName());
            $col    =   explode(',',$seqNoList);
            //启动事务
            $model->startTrans();
            foreach($col as $val) {
                $val    =   explode(':',$val);
                $model->id	=	$val[0];
                $model->sort	=	$val[1];
                $result =   $model->save();
                if(false === $result) {
					break;
                }
                //echo $model->getlastsql();
            }
            //提交事务
            $model->commit();
            if(false !== $result) {
                //采用普通方式跳转刷新页面
                $this->success('更新成功');
            }else {
                $this->error($model->getError());
            }
        }
    }

    // 查看某个模块的标签相关的记录
    public function tag()
    {
        $Tag = M("Tag");
        $name=trim($_GET['tag']);
        $Stat  = $Tag->where('module="'.$this->getActionName().'" and name="'.$name.'"')->field("id,count")->find();
        $tagId  =  $Stat['id'];
        $count   =  $Stat['count'];
        $Model = M($this->getActionName());
        $Tagged = M("Tagged");
        $recordIds  =  $Tagged->where("module='".$this->getActionName()."' and tag_id=".$tagId)->getField('id,record_id');
        if($recordIds) {
            $map['id']   = array('IN',$recordIds);
            $this->_list($Model,$map);
            $this->display('index');
        }else{
            $this->error('标签没有对应的文章！');
        }
    }
	function push(){
        //id/34/field/status/model//value/
		$id=$_GET['id'];
        $field=empty($_GET['field']) ? "status":$_GET['field'];
        $value=empty($_GET['value']) ? array('exp','-('.$field.'-1)'):$_GET['value'];
        $model=empty($_GET['model']) ? $this->getActionName() :$_GET['model'];
		$model = M($model);
		$condition = array('id'=>array('in',$id));
		if($model->data(array($field=>$value))->where($condition)->save()){
            $this->assign("jumpUrl",$_SERVER['HTTP_REFERER']);
			$this->success('操作成功！');
		}else {
			$this->error('操作失败！'.$model->getlastsql());
		}
	}

    function checkTitle($module=null){
        $module= is_null($module) ? $this->getActionName() : $module;
        $model=D($module);
        if ($model->checkTitle($_GET['title'],$_GET['id'])){
            $this->success('该标题可以使用');
        }else{
            $this->success('该标题已被使用'); 
        }
    }
    function checkName($module=null){
        $module=is_null($module) ? $this->getActionName() : $module;
        $model=D($module);
        if ($model->checkName($_GET['name'],$_GET['id'])){
            $this->success('该标识可以使用');
        }else{
            $this->success('该标识已被使用'); 
        }
    }
    /**
     * 删除整个目录
     * @param $dir
     * @return bool
     */
    function delDir( $dir )
    {
        //先删除目录下的所有文件：
        $dh = opendir( $dir );
        while ( $file = readdir( $dh ) ) {
            if ( $file != "." && $file != ".." ) {
                $fullpath = $dir . "/" . $file;
                if ( !is_dir( $fullpath ) ) {
                    unlink( $fullpath );
                } else {
                    delDir( $fullpath );
                }
            }
        }
        closedir( $dh );
        //删除当前文件夹：
        return rmdir( $dir );
    }
}
?>